package world.xuewei.component;

import cn.hutool.json.JSONObject;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.util.Assert;
import world.xuewei.model.vo.PayVo;
import lombok.Data;
import org.springframework.stereotype.Component;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.PostConstruct;

@Component
@ConfigurationProperties(prefix = "alipay")
@Data
public class AlipayTemplate {
    private static final Logger log = LoggerFactory.getLogger(AlipayTemplate.class);

    private String appId;
    private String merchantPrivateKey;
    private String alipayPublicKey;
    private String notifyUrl;
    private String returnUrl;
    private String signType;
    private String charset;
    private String gatewayUrl;

    @PostConstruct
    public void init() {
        Assert.hasText(appId, "appId 不能为空");
        Assert.hasText(merchantPrivateKey, "merchantPrivateKey 不能为空");
        Assert.hasText(alipayPublicKey, "alipayPublicKey 不能为空");
        Assert.hasText(notifyUrl, "notifyUrl 不能为空");
        Assert.hasText(returnUrl, "returnUrl 不能为空");
        log.info("支付宝配置初始化完成");
    }

    public String pay(PayVo vo) throws Exception {
        // 参数校验
        Assert.hasText(vo.getOutTradeNo(), "订单号不能为空");
        Assert.hasText(vo.getTotalAmount(), "支付金额不能为空");
        Assert.hasText(vo.getSubject(), "订单标题不能为空");

        // 创建支付客户端
        AlipayClient alipayClient = new DefaultAlipayClient(
                gatewayUrl,
                appId,
                merchantPrivateKey,
                "json",
                charset,
                alipayPublicKey,
                signType);

        // 创建支付请求
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(returnUrl);
        alipayRequest.setNotifyUrl(notifyUrl);

        // 构建请求参数
        String bizContent = String.format(
                "{\"out_trade_no\":\"%s\"," +
                        "\"total_amount\":\"%s\"," +
                        "\"subject\":\"%s\"," +
                        "\"body\":\"%s\"," +
                        "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}",
                vo.getOutTradeNo(),
                vo.getTotalAmount(),
                vo.getSubject(),
                vo.getBody()
        );
        alipayRequest.setBizContent(bizContent);

        // 调用SDK生成表单
        String result = alipayClient.pageExecute(alipayRequest).getBody();

        log.info("支付宝响应：{}", result);
        return result;
    }


    public String payForMiniProgram(PayVo vo) throws Exception {
        // 参数校验
        Assert.hasText(vo.getOutTradeNo(), "订单号不能为空");
        Assert.hasText(vo.getTotalAmount(), "支付金额不能为空");
        Assert.hasText(vo.getSubject(), "订单标题不能为空");

        // 创建支付客户端
        AlipayClient alipayClient = new DefaultAlipayClient(
                gatewayUrl,
                appId,
                merchantPrivateKey,
                "json",
                charset,
                alipayPublicKey,
                signType);

        // 创建手机网站支付请求
        AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();
        alipayRequest.setReturnUrl(returnUrl);
        alipayRequest.setNotifyUrl(notifyUrl);

        // 构建请求参数
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", vo.getOutTradeNo());
        bizContent.put("total_amount", vo.getTotalAmount());
        bizContent.put("subject", vo.getSubject());
        bizContent.put("product_code", "QUICK_WAP_WAY");
        bizContent.put("quit_url", returnUrl); // 添加退出URL

        alipayRequest.setBizContent(bizContent.toString());

        String result = alipayClient.pageExecute(alipayRequest).getBody();
        log.info("支付宝响应：{}", result);

        // 返回支付链接
        return result;
    }


    @Bean
    public AlipayClient alipayClient() {
        return new DefaultAlipayClient(
                gatewayUrl,
                appId,
                merchantPrivateKey,
                "json",
                charset,
                alipayPublicKey,
                signType
        );
    }
}